package com.dragonsoftbravo.sqlbuilder.sql;

import com.dragonsoftbravo.sqlbuilder.sql.where.builder.Comp;


public class Builder {
    protected StringBuilder sqlBuilder;
    protected String sql;

    public Builder(StringBuilder sqlBuilder) {
        this.sqlBuilder = sqlBuilder;
    }

    /**
     * just return the normal sql;
     *
     * @return
     */
    public String build() {
        return build(false, false);
    }

    /**
     * format sql befor return
     *
     * @return
     */
    public String format() {
        return build(true, false);
    }

    /**
     * get sql and auto print
     *
     * @return
     */
    public String println() {
        return build(false, true);
    }

    /**
     * custom the sql style
     *
     * @param format  format the sql if true
     * @param println print to console befor return
     * @return
     */
    public String build(boolean format, boolean println) {
        if (format) {
            sql = sqlBuilder.toString()
                    .replaceAll("WHERE", "\nWHERE")
                    .replaceAll("LIMIT", "\nLIMIT")
                    .replaceAll("GROUP BY", "\nGROUP BY")
                    .replaceAll("HAVING", "\nHAVING")
                    .replaceAll("ORDER BY", "\nORDER BY")
                    .replaceAll(" SET", " \nSET")
                    .replaceAll("VALUES ", "\nVALUES \n");
        } else {
            if (this instanceof Comp) {
                sql = "(" + sqlBuilder.toString() + ")";
            } else {
                sql = sqlBuilder.toString();
            }
        }

        if (println) {
            System.out.println(sql);
        }
        return sql;
    }
}
